import 'dart:io';
import 'dart:typed_data';
import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:gallery_saver/gallery_saver.dart';
import 'package:path_provider/path_provider.dart';
import 'package:qr_flutter/qr_flutter.dart';

class QrGenerator extends StatefulWidget {
  @override
  _QrGeneratorState createState() => _QrGeneratorState();
}

class _QrGeneratorState extends State<QrGenerator> {
  var _data = '';
  var key = GlobalKey();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('二维码生成'),
      ),
      body: RepaintBoundary(
        key: key,
        child: Container(
          color: Colors.white,
          child: ListView(
            children: <Widget>[
              QrImage(
                size: 200,
                data: _data,
              ),
              TextField(
                onChanged: (v) => _data = v,
              ),
              RaisedButton(
                child: Text('生成'),
                onPressed: () {
                  if (_data.isEmpty) return;
                  setState(() {});
                },
              ),
              RaisedButton(
                child: Text('导出图片'),
                onPressed: () {
                  if (_data.isEmpty) return;
                  exportImage();
                },
              ),
            ],
          ),
        ),
      ),
    );
  }

  Uint8List exported;

  exportImage() async {
    // var data = await QrPainter(data: _data).toImageData(200);
    RenderRepaintBoundary boundary = key.currentContext.findRenderObject();
    var image = await boundary.toImage();
    var data = await image.toByteData(format: ImageByteFormat.png);
    exported = data.buffer.asUint8List();
    var dir = await getApplicationDocumentsDirectory();
    var file =
        new File('${dir.path}/${DateTime.now().millisecondsSinceEpoch}.png');
    await file.writeAsBytes(exported);
    await GallerySaver.saveImage(file.path);
    showDialog(
        context: context,
        builder: (_) {
          return AlertDialog(
            content: Image.memory(
              exported,
              fit: BoxFit.contain,
            ),
          );
        });
  }
}
